package com.android.lovely.ui.fragment

import android.graphics.Paint
import android.text.Html
import android.util.Log
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.android.lovely.R
import com.android.lovely.aav.PreferentialManager
import com.android.lovely.aav.PreferentialManager.playEnter
import com.android.lovely.data.HomeTabData
import com.android.lovely.databinding.FragmentHomeBinding
import com.android.lovely.framework.BaseFragment
import com.android.lovely.framework.BaseMvvmFragment
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.activity.CustomLanguagePickerActivity
import com.android.lovely.ui.activity.LifecycleActivity
import com.android.lovely.ui.activity.PayActivity
import com.android.lovely.ui.activity.SearchActivity
import com.android.lovely.ui.dialog.PreferentialDialog
import com.android.lovely.ui.dialog.showLovelyDialog
import com.android.lovely.ui.viewmodel.HomeViewModel
import com.android.lovely.user.UserManager
import com.android.lovely.user.UserManager.registerAuthChange
import com.google.android.material.tabs.TabLayoutMediator
import com.kotlin.extensions.appContext
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest
import kotlin.math.abs

/**
 *
 * @author why
 * @date 2025/3/9 16:54
 */
class HomeFragment : BaseFragment<FragmentHomeBinding>() {

    private val mViewModel by activityViewModels<HomeViewModel>()

    private val adapter by lazy {
        HomeAdapter(childFragmentManager, lifecycle)
    }

    override suspend fun initData() {
        mViewModel.homeTabList.collectLatest {
            updateTags(it)
        }
    }

    override fun initView() {
        mBinding.rlTop.addStatusBarMarginTop()
        mBinding.tvDiamond.clickable {
            startPage<PayActivity>()
        }
        mBinding.ivSearch.clickable {
            startPage<SearchActivity>()
        }
        mBinding.appBarLayout.addOnOffsetChangedListener { appBarLayout, i ->
            if (abs(i) == appBarLayout.totalScrollRange) {
                mBinding.ivSearch.isVisible = true
            } else {
                mBinding.ivSearch.isVisible = false
            }
        }
        registerAuthChange {
            mBinding.lifecycle.isVisible = it.isVip().not() && UserManager.isB()
            if (it.isVip().not()) mBinding.preferential.isVisible = false
            mBinding.tvDiamond.text = it.point.toString()
            mBinding.nsfwSwitch.isSelected = it.nsfwStatus == 1
        }
        viewLifecycleOwner.lifecycleScope.launchSafety {
            PreferentialManager.eventFlow.collectLatest {
                if (UserManager.isVip() && UserManager.isB()) {
                    mBinding.preferential.isVisible = true
                    mBinding.preferential.playEnter()
                } else {
                    mBinding.preferential.isVisible = false
                }
            }
        }
        mBinding.nsfwSwitch.isVisible = !UserManager.isC()
        mBinding.nsfwSwitch.clickable {
            val isSelect = it.isSelected
            if (isSelect) {
                requireActivity().showLovelyDialog {
                    setDialogTitle(getString(R.string.nsfw_switch_title))
                    setDialogMessage(getString(R.string.nsfw_switch_message))
                    setNegativeButton(getString(R.string.confirm)) {
                        mBinding.nsfwSwitch.isSelected = false
                        mViewModel.changeNsfw(0)
                    }
                    setPositiveButton(getString(R.string.cancel))
                }
            } else {
                mBinding.nsfwSwitch.isSelected = true
                mViewModel.changeNsfw(1)
            }
        }
        mBinding.viewPager.adapter = adapter
        mBinding.viewPager.offscreenPageLimit = adapter.itemCount
        mBinding.search.clickable {
            startPage<SearchActivity>()
        }
        mBinding.edgeLayout.clickable {
            if (mBinding.lifecycle.isVisible) startPage<LifecycleActivity>()
            if (mBinding.preferential.isVisible){
                if (PreferentialManager.isEnable) PreferentialDialog().show(childFragmentManager)
                else mBinding.preferential.isVisible = false
            }
        }
        TabLayoutMediator(
            mBinding.llTabLayout,
            mBinding.viewPager,
            getTabConfigurationStrategy()
        ).attach()
        mViewModel.getTabs()
    }

    private fun getTabConfigurationStrategy() =
        TabLayoutMediator.TabConfigurationStrategy { tab, position ->
            tab.text = adapter.getTitle(position)
        }

    private fun updateTags(tags: List<HomeTabData>) {
        mBinding.llTabLayout.post {
            adapter.updateTags(tags)
        }
    }
}

class HomeAdapter(fragmentManager: FragmentManager, lifeCircle: Lifecycle) : FragmentStateAdapter(fragmentManager, lifeCircle) {

    private val tabs by lazy {
        mutableListOf(HomeTabData(null, appContext.getString(R.string.recommend)))
    }

    fun updateTags(tags: List<HomeTabData>) {
        val size = tabs.size
        tabs.removeRange(1, size - 1)
        notifyItemRangeRemoved(1, size - 1)
        tabs.addAll(tags)
        notifyItemRangeInserted(1, tags.size)

    }

    override fun getItemCount(): Int {
        return tabs.size
    }

    fun getTitle(position: Int): String {
        return tabs[position].roleName
    }

    fun <T> MutableList<T>.removeRange(fromIndex: Int, toIndex: Int) {
        if (fromIndex >= size) {
            return
        }
        val subList: MutableList<T> = subList(fromIndex, toIndex + 1)
        subList.clear()
    }

    override fun createFragment(position: Int): Fragment {
        return HomeListFragment().apply {
            if (tabs[position].id != null) {
                arguments = bundleOf("tab" to tabs[position].id)
            }
        }
    }
}

